package inet.app.view.activity;

import inet.app.R;
import inet.app.model.object.ContactModel;
import inet.app.model.util.BitmapUtil;
import inet.app.model.util.ContactVersionIIUtil;
import inet.app.model.util.KeyboardUtil;
import inet.app.model.util.SmartLog;
import inet.app.model.util.Util;
import inet.app.stickylistheaders.StickyListHeadersListView;
import inet.app.view.adapter.ContactAdapter;
import inet.app.view.widget.SlidingLayer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class InviteFriendsActivity extends BaseFragmentActivity implements
		View.OnClickListener, OnItemClickListener {
//	private final String CONTENT_SMS = "Mời bạn sử dụng cùng tôi ứng dụng Xổ Số 3 Miền. \nDownload: https://play.google.com/store/apps/details?id=inet.app";
	private final String CONTENT_SMS = "Tôi đang sử dụng ứng dụng Xổ Số 3 Miền, ứng dụng rất hay và tiện dụng. Hãy sử dụng cùng tôi! \nDownload: https://play.google.com/store/apps/details?id=inet.app";
	private StickyListHeadersListView mContactList;
	private ContactAdapter mContactAdapter;
	private List<ContactModel> mContactModels = new ArrayList<ContactModel>();
	private List<Boolean> mSelector = new ArrayList<Boolean>();
	private List<ContactModel> mContactSend = new ArrayList<ContactModel>();
	private ProgressBar mLoadingView;
	private AsyncTask<Void, Void, Boolean> mLoadContactTask;
	private SlidingLayer mLayerSendSms;
	private EditText mListContactSend;

	private Bitmap mArrowUpBmp;
	private Bitmap mArrowDownBmp;
	private EditText mSmsEdt;
	private Button mSendBtn;
	private long mStartTime;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_invite_friends);
		initBase();
		initModels();
		initViews();
	}

	public void initModels() {
		// create bitmap for arrow down and up
		if (mArrowDownBmp == null) {
			mArrowDownBmp = BitmapUtil.rotateBitmap(this,
					R.drawable.btn_back_on, -90);
		}
		if (mArrowUpBmp == null) {
			mArrowUpBmp = BitmapUtil.rotateBitmap(this, R.drawable.btn_back_on,90);
		}
	}

	public void initViews() {
		mContactList = (StickyListHeadersListView) findViewById(R.id.contact_list);
		mContactList.setDrawingListUnderStickyHeader(true);
		mContactList.setAreHeadersSticky(true);
		mContactList.setOnItemClickListener(this);
		mLoadingView = (ProgressBar) findViewById(R.id.loading);
		attachViewSendSMS();
		mSmsEdt.setText(CONTENT_SMS);
		TextView title = (TextView) findViewById(R.id.tvTitle);
		title.setText(getString(R.string.moi_ban_be));
	}

	/**
	 * Attach view send sms to bottom
	 */
	private void attachViewSendSMS() {
		mLayerSendSms = new SlidingLayer(this);
		View slideView = LayoutInflater.from(this).inflate(
				R.layout.view_sms_invite_friends, null);
		mSmsEdt = (EditText) slideView.findViewById(R.id.content_sms);
		mSendBtn = (Button) slideView.findViewById(R.id.send_btn);
		mSendBtn.setOnClickListener(this);

		// don't fill text to this edit text.
		mListContactSend = (EditText) slideView.findViewById(R.id.contact_send);
		mListContactSend.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return true;
			}
		});

		// full height of slide menu
		int height = (int) getResources().getDimension(
				R.dimen.view_send_sms_height);
		RelativeLayout.LayoutParams wrapParams = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.MATCH_PARENT, height);
		wrapParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		mLayerSendSms.setLayoutParams(wrapParams);
		mLayerSendSms.addView(slideView);
		mLayerSendSms.setStickTo(SlidingLayer.STICK_TO_BOTTOM);

		// height of slide menu if close
		float padding = getResources().getDimension(
				R.dimen.view_send_sms_padding);
		mLayerSendSms
				.setOffsetWidth((int) (mArrowUpBmp.getHeight() + 3 * padding));

		// change orientation of arrow view when open or close slide menu
		final ImageView arrowView = (ImageView) slideView
				.findViewById(R.id.arrow_image);
		arrowView.setImageBitmap(mArrowUpBmp);
		arrowView.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				KeyboardUtil.hideSoftKeyboard(InviteFriendsActivity.this);
				return false;
			}
		});

		mLayerSendSms.setOnInteractListener(new SlidingLayer.OnInteractListener() {

					@Override
					public void onOpened() {
						arrowView.setImageBitmap(mArrowDownBmp);
					}
					@Override
					public void onOpen() {
					}
					@Override
					public void onClosed() {
						arrowView.setImageBitmap(mArrowUpBmp);
					}

					@Override
					public void onClose() {
					}
				});
		RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.main_layout);
		mainLayout.addView(mLayerSendSms);
	}

	@Override
	public void onResume() {
		super.onResume();
		synchronizeContact();
	}

	private void synchronizeContact() {

		if (mLoadContactTask != null) {
			return;
		}

		mLoadContactTask = new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				mContactModels = new ArrayList<ContactModel>();
				mContactList.setVisibility(View.GONE);
				mLoadingView.setVisibility(View.VISIBLE);
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				// mContactModels = ContactVersionIIUtil.getInstance(
				// getApplicationContext()).getListContact();
				mContactModels = ContactVersionIIUtil.getInstance(
						getApplicationContext()).getListContactSimple();
				if (mContactModels == null || mContactModels.size() == 0) {
					return false;
				}
				SmartLog.d("time load contact before filter: "
						+ (System.currentTimeMillis() - mStartTime));
				Iterator<ContactModel> iterator = mContactModels.iterator();

				// show contacts has phone number
				ContactModel contactModel;
				while (iterator.hasNext()) {
					contactModel = iterator.next();
					if (TextUtils.isEmpty(contactModel.phoneNumber)) {
						iterator.remove();
					} else {
						mSelector.add(false);
					}
				}
				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				mLoadContactTask = null;
				mContactList.setVisibility(View.VISIBLE);
				mLoadingView.setVisibility(View.GONE);

				if (!result) {
					Toast.makeText(getApplicationContext(),
							"Không tìm thấy danh bạ", Toast.LENGTH_LONG).show();
					return;
				}
				mSendBtn.setClickable(true);
				SmartLog.d("time load contact: "
						+ (System.currentTimeMillis() - mStartTime));
				mContactAdapter = new ContactAdapter(
						InviteFriendsActivity.this, 0, mContactModels,
						mSelector);
				mContactList.setAdapter(mContactAdapter);
			}
		};
		mStartTime = System.currentTimeMillis();
		mLoadContactTask.execute();
	}

	@Override
	public void onStop() {
		super.onStop();
		if (mLoadContactTask != null
				&& mLoadContactTask.getStatus() == Status.RUNNING) {
			mLoadContactTask.cancel(true);
			mLoadContactTask = null;
			mContactList.setVisibility(View.VISIBLE);
			mLoadingView.setVisibility(View.GONE);
		}
	}
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			System.out.println("THOAT NHE");
			showQuitDialog(InviteFriendsActivity.this);
			dlquit.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.send_btn:
			mLayerSendSms.closeLayer(true);
			sendSms();
			break;

		default:
			break;
		}
	}

	private void sendSms() {

		boolean isValid = validateFields();
		if (!isValid) {
			return;
		}
		KeyboardUtil.hideSoftKeyboard(InviteFriendsActivity.this);
		String smsContent = mSmsEdt.getText().toString();
		for (ContactModel contact : mContactSend) {
			Util.sendSMS(smsContent, contact.getPhoneNumber(), this);
			SmartLog.d("send to " + contact.getPhoneNumber());
		}
		Toast.makeText(getApplicationContext(), "Đã gửi tin nhắn",
				Toast.LENGTH_SHORT).show();
	}

	private boolean validateFields() {

		String error = "";
		boolean isValid = true;
		if (TextUtils.isEmpty(mSmsEdt.getText())) {
			error = getString(R.string.dien_noi_dung_tin_nhan);
			isValid = false;
		} else if (mContactSend.size() == 0) {
			error = getString(R.string.chon_nguoi_gui);
			isValid = false;
		}
		if (!isValid) {
			Toast.makeText(InviteFriendsActivity.this, error,
					Toast.LENGTH_SHORT).show();
		}
		return isValid;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		boolean isSelect = mSelector.get(position);
		isSelect = !isSelect;
		mSelector.set(position, isSelect);
		ContactModel contact = mContactModels.get(position);
		if (isSelect) {
			mContactSend.add(contact);
		} else {
			mContactSend.remove(contact);
		}

		// edit text list contact send
		StringBuffer listSend = new StringBuffer(getString(R.string.gui_toi));
		for (ContactModel contactSend : mContactSend) {
			listSend = listSend.append(contactSend.getContactName()).append(
					", ");
		}
		mListContactSend.setText(listSend.toString());
		mContactAdapter.notifyDataSetChanged();
	}

}
